import React, { useState, useEffect } from 'react';
import axios from 'axios';
import './EmailForm.css';  // 引入 CSS 文件

const EmailForm = () => {
    const [smtpUser, setSmtpUser] = useState('');
    const [smtpPassword, setSmtpPassword] = useState('');
    const [subject, setSubject] = useState('');
    const [body, setBody] = useState('');
    const [emailFile, setEmailFile] = useState(null);
    const [attachmentFiles, setAttachmentFiles] = useState([]);  // 修改为数组以支持多个附件
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const [result, setResult] = useState(null);  // 用于存储后端返回结果
    const [progress, setProgress] = useState(0);  // 进度条值

    useEffect(() => {
        const socket = new WebSocket('ws://127.0.0.1:8000/ws/send-email');

        socket.onopen = () => {
            console.log('WebSocket connected');
        };

        socket.onmessage = (event) => {
            const data = JSON.parse(event.data);  // 解析为 JSON
            if (data.progress !== undefined) {
                setProgress(data.progress);  // 更新进度条
            } else {
                setResult(data);  // 处理其他响应
            }
        };

        socket.onerror = (event) => {
            console.error('WebSocket error', event);
        };

        socket.onclose = () => {
            console.log('WebSocket disconnected');
        };

        return () => {
            socket.close();
        };
    }, []);

    const handleSubmit = async (e) => {
        e.preventDefault();
        setLoading(true);
        setError(null);
        setResult(null);  // 清除上一个结果
        setProgress(0);  // 重置进度条

        const formData = new FormData();
        formData.append('smtp_user', smtpUser);
        formData.append('smtp_password', smtpPassword);
        formData.append('subject', subject);
        formData.append('body', body);
        formData.append('file', emailFile);

        // 将所有附件文件添加到 FormData
        attachmentFiles.forEach(file => {
            formData.append('attachments', file);  // 添加每个文件
        });

        try {
            const response = await axios.post('http://127.0.0.1:8000/send-email', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
            });

            // 更新结果状态
            setResult(response.data);
        } catch (error) {
            setError('An error occurred while sending emails.');  // 通用错误信息
            console.error('Error:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleAttachmentChange = (e) => {
        setAttachmentFiles(Array.from(e.target.files));  // 将文件列表转换为数组
    };

    return (
        <div className="email-form-container">
            <h1>Send Emails</h1>
            <form onSubmit={handleSubmit} className="email-form">
                <div className="form-group">
                    <label>SMTP User:</label>
                    <input type="text" value={smtpUser} onChange={(e) => setSmtpUser(e.target.value)} required />
                </div>
                <div className="form-group">
                    <label>SMTP Password:</label>
                    <input type="password" value={smtpPassword} onChange={(e) => setSmtpPassword(e.target.value)} required />
                </div>
                <div className="form-group">
                    <label>Subject:</label>
                    <input type="text" value={subject} onChange={(e) => setSubject(e.target.value)} required />
                </div>
                <div className="form-group">
                    <label>Body:</label>
                    <textarea value={body} onChange={(e) => setBody(e.target.value)} required />
                </div>
                <div className="form-group">
                    <label>Email List (Excel File):</label>
                    <input type="file" accept=".xlsx,.xls" onChange={(e) => setEmailFile(e.target.files[0])} required />
                </div>
                <div className="form-group">
                    <label>Attachments (Select multiple files):</label>
                    <input
                        type="file"
                        accept=".png,.jpg,.jpeg,.pdf,.doc,.docx,.txt,.xls,xlsx" // 允许的文件类型，根据需要修改
                        multiple
                        onChange={handleAttachmentChange}
                        required
                    />
                </div>
                <button type="submit" disabled={loading} className="submit-button">{loading ? 'Sending...' : 'Send Emails'}</button>
            </form>

            <div className="progress-bar-container">
                <div className="progress-bar" style={{ width: `${progress}%` }}>{`${progress}%`}</div>
            </div>

            {error && <p className="error-message">{error}</p>}
            {result && (
                <div className="result-container">
                    <h2>{result.message}</h2>
                    {result.successfully_sent && result.successfully_sent.length > 0 && (
                        <div>
                            <h3>Successfully Sent:</h3>
                            <ul>
                                {result.successfully_sent.map((email, index) => (
                                    <li key={index}>{email}</li>
                                ))}
                            </ul>
                        </div>
                    )}
                    {result.failed_to_send && result.failed_to_send.length > 0 && (
                        <div>
                            <h3>Failed to Send:</h3>
                            <ul>
                                {result.failed_to_send.map((error, index) => (
                                    <li key={index}>{error}</li>
                                ))}
                            </ul>
                        </div>
                    )}
                </div>
            )}
        </div>
    );
};

export default EmailForm;
